﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Enterprise
{
    /// <summary>
    /// 添加企业信息
    /// </summary>
    public class CreateEnterpriseHandler : IRequestHandler<CreateEnterpriseCommand, Result>
    {
        private readonly IMapper _mapper;
        /// <summary>
        /// 企业仓储
        /// </summary>
        private readonly IBaseRepository<Enterprises> _enterpriseRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateEnterpriseHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="enterpriseRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public CreateEnterpriseHandler(IBaseRepository<Enterprises> enterpriseRepository,
                                       ILogger<CreateEnterpriseHandler> logger,
                                       IMapper mapper)
        {
            _enterpriseRepository = enterpriseRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加企业信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreateEnterpriseCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //判断该企业是否存在
                var query = await (await _enterpriseRepository.GetAll()).Where(j => j.EnterpriseName == request.EnterpriseName).CountAsync();
                if (query > 0)
                {
                    result.Code = (int)CommonErrorCode.Added;
                    result.Msg = "该企业已被注册,请重新输入";
                }
                else
                {
                    //将信息转换为类
                    Enterprises enter = _mapper.Map<Enterprises>(request);
                    //添加数据
                    var res = await _enterpriseRepository.Add(enter);
                    //判断是否添加成功
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "添加企业信息成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加企业信息异常" + ex.Message;
                _logger.LogError("添加企业信息异常" + ex.Message);
            }
            return result;
        }
    }
}
